﻿using Furion.JsonSerialization;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.Extension
{
    public static class DataTableExtensions
    {
        
        /// <summary>
        /// 将DataTable 转换成 List
        /// </summary>
        /// <param name="table"></param>
        /// <param name="reverse">reverse 反转：控制返回结果中是只存在 FilterField 指定的字段,还是排除.</param>
        /// <param name="FilterField">FilterField  字段过滤，FilterField 为空 忽略 reverse 参数；返回DataTable中的全部数</param>
        /// <returns></returns>
        public static List<dynamic> ToDynamicList(this DataTable table, bool reverse = true, params string[] FilterField)
        {
            var modelList = new List<dynamic>();
            foreach (DataRow row in table.Rows)
            {
                dynamic model = new ExpandoObject();
                var dict = (IDictionary<string, object>)model;
                foreach (DataColumn column in table.Columns)
                {
                    if (FilterField.Length != 0)
                    {
                        if (reverse == true)
                        {
                            if (!FilterField.Contains(column.ColumnName))
                            {
                                dict[column.ColumnName] = row[column];
                            }
                        }
                        else
                        {
                            if (FilterField.Contains(column.ColumnName))
                            {
                                dict[column.ColumnName] = row[column];
                            }
                        }
                    }
                    else
                    {
                        dict[column.ColumnName] = row[column];
                    }
                }
                modelList.Add(model);
            }
            return modelList;
        }

        public static string ToJson(this DataTable dt)
        {
            //JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
           // javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = new ArrayList();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                }
                arrayList.Add(dictionary); //ArrayList集合中添加键值
            }

            return JSON.GetJsonSerializer().Serialize(arrayList);  //返回一个json字符串
        }
    }
}
